package com.medical.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.medical.common.core.domain.Result;
import com.medical.common.core.utils.StringUtils;
import com.medical.common.core.utils.bean.BeanUtils;
import com.medical.common.security.utils.SecurityUtils;
import com.medical.manage.domain.Article;
import com.medical.manage.domain.ArticleTopic;
import com.medical.manage.domain.BrowseRecording;
import com.medical.manage.domain.vo.ArticleVo;
import com.medical.manage.mapper.ArticleMapper;
import com.medical.manage.service.ArticleService;
import com.medical.manage.service.ArticleTopicService;
import com.medical.manage.service.BrowseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;
    @Autowired
    private BrowseService browseService;
    @Autowired
    private ArticleTopicService articleTopicService;

    /**
     * 文章案例
     * @return
     */
    @Override
    public List<?> getDemoArticle() {
        //根据文章类型查询案例文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getArticleType,2);
        List<Article> list = list(queryWrapper);
        BeanUtils.copyBeanProp(list, ArticleVo.class);
        return list;
    }

    /**
     * 文章案例详情
     * @return
     */
    @Override
    public Result getArticleDetail(Integer id) {
        //根据文章id查询文章详情
        QueryWrapper<Article> wrapper = new QueryWrapper<>();
        wrapper.eq("article_type", 2)
                .eq("id", id);
        Article article = getOne(wrapper);
        BeanUtils.copyBeanProp(article, ArticleVo.class);
        return Result.success(article);
    }

    /**
     * 发布文章
     * @param articleVo
     */
    @Override
    public Result publishArticle(ArticleVo articleVo) {
        /*//非空判断
        if(StringUtils.isBlank(articleVo.getTitle()) || StringUtils.isBlank(articleVo.getArticleContent()) || articleVo.getTopicId()==null ){
            return Result.error("文章标题、内容、话题不能为空");
        }*/
        //获取发布人id
        Long userId = SecurityUtils.getUserId();
        //发布文章
        articleVo.setCreateTime(new Date());
        articleVo.setUpdateTime(new Date());
        articleVo.setUserId(userId);
        articleVo.setArticleType(1);
        //添加文章
        articleMapper.publishArticle(articleVo);
        //发布成功之后，修改文章状态为 2（发步成功）
        articleVo.setState(2);
        articleMapper.updateStateById(articleVo.getId(), articleVo.getState());
        // 添加文章话题中间表
        List<Integer> topicIds = articleVo.getTopicIds();
        if (topicIds != null && !topicIds.isEmpty()) {
            topicIds.forEach(topicId -> {
                // 每次循环创建新的对象，避免属性覆盖
                ArticleTopic articleTopic = new ArticleTopic();
                articleTopic.setArticleId(articleVo.getId());
                articleTopic.setTopicId(topicId);
                articleTopic.setUserId(userId);
                articleTopicService.save(articleTopic);
            });
        }
        return Result.success("发布成功");
    }

    /**
     * 保存到草稿箱
     * @param articleVo
     */
    @Override
    public void saveDraft(ArticleVo articleVo) {
        //保存到草稿箱
        articleMapper.publishArticle(articleVo);
        //保存成功，修改文章状态为 1 （草稿箱）
        articleVo.setState(1);
        articleMapper.updateStateById(articleVo.getId(),articleVo.getState());
    }

    /**
     * 草稿箱列表
     * @return
     */
    @Override
    public Result<List<Article>> getDraft() {
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        //根据状态查询草稿箱列表
        queryWrapper.eq(Article::getState,1);
        List<Article> list = list(queryWrapper);
        return Result.success(list);
    }

    /**
     * 我创作的文章
     * @return
     */
    @Override
    public Result<List<Article>> getMyCreation() {
        //根据状态查询创作列表
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getState,2);
        List<Article> list = list(queryWrapper);
        return Result.success(list);
    }

    /**
     * 查看创作文章详情
     * @return
     */
    @Override
    public Result getCreateArticleDetail(Integer id) {
        //根据文章id查询文章详情
        ArticleVo articleVo=articleMapper.getCreateArticleDetail(id);
        //添加一条浏览记录
        Long userId = SecurityUtils.getUserId();
        BrowseRecording browseRecording = new BrowseRecording();
        browseRecording.setArticleId(id);
        browseRecording.setUserId(userId);
       /* browseService.addBrowseRecording(browseRecording);*/
        browseService.save(browseRecording);
        return Result.success(articleVo);
    }

    /**
     * 推荐阅读文章
     * @param id
     * @return
     */
    @Override
    public Result<List<ArticleVo>> recommendReadArticle(Integer id) {
        List<ArticleVo> list=articleMapper.recommendReadArticle(id);
        return Result.success(list);
    }


}
